using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using AjGenesisStudio.Tools;

namespace AjGenesisStudio.Commands
{
    class ExecuteExternalToolCommand : Command
    {
        public ExecuteExternalToolCommand() { }

        public ExecuteExternalToolCommand(ExternalTool tool)
        {
            this.tool = tool;
        }

        private ExternalTool tool;

        public ExternalTool Tool
        {
            get { return tool; }
            set { tool = value; }
        }
	
        public override bool Execute()
        {
            Global.Instance.StartWork("Executing " + tool.Title);

            Process proc;
            bool res = false;

            proc = new Process();
            if (Directory.Exists(tool.WorkingDirectory))
                proc.StartInfo.WorkingDirectory = tool.WorkingDirectory;
            proc.StartInfo.FileName = tool.Command;
            proc.StartInfo.Arguments = tool.Arguments;

            try
            {
                if (tool.UseOuputWindow)
                {
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.ErrorDialog = false;
                    proc.StartInfo.CreateNoWindow = true;
                    proc.StartInfo.RedirectStandardOutput = true;
                    res = proc.Start();
                    while (!proc.HasExited)
                    {
                        string line = proc.StandardOutput.ReadLine();
                        if (!string.IsNullOrEmpty(line))
                            Global.Instance.LogLine(line);
                    }
                    proc.WaitForExit();
                }
                else
                {
                    res = proc.Start();
                }
            }
            catch (System.ComponentModel.Win32Exception exwin)
            {
                if (exwin.ErrorCode == -2147467259)
                    MessageBox.Show("The executable does not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(exwin.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Global.Instance.EndWork();
            }

            return res;
        }

    }
}
